package drds.common.db.xml_mapping.session.defaults;

import drds.common.db.xml_mapping.exceptions.ExceptionFactory;
import drds.common.db.xml_mapping.executor.Executor;
import drds.common.db.xml_mapping.mapping.Environment;
import drds.common.db.xml_mapping.session.Configuration;
import drds.common.db.xml_mapping.session.ExecutorType;
import drds.common.db.xml_mapping.session.MapperContext;
import drds.common.db.xml_mapping.session.SqlSessionFactory;
import drds.common.db.xml_mapping.transaction.JdbcTransactionFactory;
import drds.common.db.xml_mapping.transaction.Transaction;
import drds.common.db.xml_mapping.transaction.TransactionFactory;

import java.sql.Connection;
import java.sql.SQLException;


public class DefaultSqlSessionFactory implements SqlSessionFactory {

  private final Configuration configuration;

  public DefaultSqlSessionFactory(Configuration configuration) {
    this.configuration = configuration;
  }

  @Override
  public MapperContext openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), false);
  }

  @Override
  public MapperContext openSession(boolean autoCommit) {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), autoCommit);
  }

  @Override
  public MapperContext openSession(ExecutorType executorType) {
    return openSessionFromDataSource(executorType, false);
  }


  @Override
  public MapperContext openSession(ExecutorType executorType, boolean autoCommit) {
    return openSessionFromDataSource(executorType, autoCommit);
  }

  @Override
  public MapperContext openSession(Connection connection) {
    return openSessionFromConnection(configuration.getDefaultExecutorType(), connection);
  }

  @Override
  public MapperContext openSession(ExecutorType executorType, Connection connection) {
    return openSessionFromConnection(executorType, connection);
  }

  @Override
  public Configuration getConfiguration() {
    return configuration;
  }

  private MapperContext openSessionFromDataSource(ExecutorType executorType, boolean autoCommit) {
    Transaction transaction = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      transaction = transactionFactory.newTransaction(environment.getDataSource().getConnection(), autoCommit);
      final Executor executor = configuration.newExecutor(transaction, executorType);
      return new DefaultMapperContext(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(transaction); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {

    }
  }

  private MapperContext openSessionFromConnection(ExecutorType executorType, Connection connection) {
    try {
      boolean autoCommit;
      try {
        autoCommit = connection.getAutoCommit();
      } catch (SQLException e) {
        // Failover to true, as most poor drivers
        // or databases won't support transactions
        autoCommit = true;
      }
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      final Transaction transaction = transactionFactory.newTransaction(connection, false);
      final Executor executor = configuration.newExecutor(transaction, executorType);
      return new DefaultMapperContext(configuration, executor, autoCommit);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {

    }
  }

  private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
    if (environment == null || environment.getTransactionFactory() == null) {
      return new JdbcTransactionFactory();
    }
    return environment.getTransactionFactory();
  }

  private void closeTransaction(Transaction tx) {
    if (tx != null) {
      try {
        tx.close();
      } catch (SQLException ignore) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

}
